package cn.tanghom.app.system.service.impl;

import cn.tanghom.app.system.mapper.OrganizationMapper;
import cn.tanghom.app.system.mapper.UserMapper;
import cn.tanghom.app.system.mapper.UserRoleMapper;
import cn.tanghom.app.system.model.Organization;
import cn.tanghom.app.system.model.Role;
import cn.tanghom.app.system.model.User;
import cn.tanghom.app.system.service.RoleService;
import cn.tanghom.app.system.service.UserService;
import cn.tanghom.support.page.Pager;
import cn.tanghom.support.utils.CommonUtils;
import cn.tanghom.support.utils.Md5Util;
import cn.tanghom.support.utils.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;

/**
 * 用户管理逻辑处理层
 *
 * @author tanghom<tanghom@qq.com> on 2016/5/16
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private UserRoleMapper userRoleMapper;
    
    @Resource
    private OrganizationMapper organizationMapper;
    
    @Autowired
    RoleService roleService;

    @Override
    public String saveOrUpdate(User user, Long roleId[]) {
        try {
            User checkUser = userMapper.findByLoginName(user.getLoginName());
            Organization organization = organizationMapper.findById(user.getOrganizationId());
            if (user.getId() == null) {// 添加
                if (checkUser != null) {
                    return CommonUtils.msgCallback(false, "登录名已存在,请换一个!", "", null);
                }
                String pwd = user.getLoginPwd();
                if (StringUtils.isNullOrEmpty(pwd)) {
                    pwd = "123456";
                }
                pwd = Md5Util.encrypt(pwd);
                user.setLoginPwd(pwd);
                user.setOrganizationId(organization.getId());
                user.setOrganizationName(organization.getName());
                user.setCreateTime(new Date());
                userMapper.save(user);

            } else {// 修改
                User u = userMapper.findById(user.getId());
                if (checkUser != null && u.getId() != checkUser.getId()) {
                    return CommonUtils.msgCallback(false, "登录名已存在,请换一个!", "", null);
                }
                u.setUserName(user.getUserName());
                u.setLoginName(user.getLoginName());
                String pwd = user.getLoginPwd();
                if (!StringUtils.isNullOrEmpty(pwd)) {
                    pwd = Md5Util.encrypt(pwd);
                    u.setLoginPwd(pwd);
                }
                u.setSex(user.getSex());
                u.setStatus(user.getStatus());
                u.setOrganizationId(organization.getId());
                u.setOrganizationName(organization.getName());
                u.setPhone(user.getPhone());
                userMapper.update(u);
                userRoleMapper.delete(user.getId(), null);
            }
            if (null != roleId) {
                int roleIdSize = roleId.length;
                for (int i = 0; i < roleIdSize; i++) {
                    userRoleMapper.save(user.getId(), roleId[i]);
                }
            }
            return CommonUtils.msgCallback(true, "操作成功", "", null);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void reg(User user) {
        //默认角色消防站
        user.setLoginPwd(Md5Util.encrypt(user.getLoginPwd()));
        user.setCreateTime(new Date());
        userMapper.save(user);
        
        Role defRole = roleService.findByNameOrKey("user","user");
        if(defRole!=null)
        	userRoleMapper.save(user.getId(), defRole.getId());
    }

    @Override
    public void save(User user) {
    	user.setLoginPwd(Md5Util.encrypt(user.getLoginPwd()));        
    	userMapper.save(user);
    	for(Role role: user.getRoles()){
    		userRoleMapper.save(user.getId(), role.getId());
    	}
    }

    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delete(Long id) {
        userMapper.delete(id);
    }

    @Override
    public User findById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    public User findByLoginName(String loginName) {
        User user = userMapper.findByLoginName(loginName);
        return user;
    }
    
    @Override
	public User findByPhone(String phone) {
    	 User user = userMapper.findByPhone(phone);
         return user;
	}

	@Override
	public User findByEmail(String email) {
		 User user = userMapper.findByEmail(email);
	     return user;
	}

    @Override
    public List<User> findList(int status) {
    	List<User> users = userMapper.findListByParams(null,null,null,status,null);
    	return users;
    }

    @Override
    public Pager<User> findPageByParams(String userName, String loginName, Long orgId, Integer status, Long index) {
        Pager<User> pager = new Pager<User>();
        pager.setIndex(index);
        pager.setSize(10);
        pager.setItems(userMapper.findPageByParams(userName, loginName, orgId, status, null, pager.startRow(), pager.getSize()));
        pager.setTotalRecord(userMapper.countByParams(userName, loginName, orgId, status, null));
        return pager;
    }

    public Pager<User> findPageByIds(String ids, String userName, String loginName, Long orgId, Long index) {
        Pager<User> pager = new Pager<User>();
        pager.setIndex(index);
        pager.setSize(10);
        pager.setItems(userMapper.findPageByParams(userName, loginName, orgId, null, ids, pager.startRow(), pager.getSize()));
        pager.setTotalRecord(userMapper.countByParams(userName, loginName, orgId, null, ids));
        return pager;
    }
    
    
    @Override
	public List<User> findUserByGroupId(Long groupId, Pager<User> page) {
//		List<User> list = findByPage("User", new String[]{"group"}, new String[]{groupId});
    	Pager<User> pager = findPageByParams(null,null,groupId,1,page.getIndex());
		return pager.getItems();
	}
    
    
    @Override
	public List<User> findUserByRole(String roleKey) {
//		List<User> list = findByPage("User", new String[]{"group"}, new String[]{groupId});
    	List<User> pager = userMapper.findListByRoleParams(roleKey,null);
		return pager;
	}
    
    public boolean hasRole(String userId, String rolekey){    	
    	User user = this.findByLoginName(userId);
  		List<Role> userroles=user.getRoles();
  		if(userroles==null || userroles.size()==0)
  			return false;
  		
  		boolean flag=false;
  		for(Role r:userroles)
  		{
  			if(r.getRoleKey().equals(rolekey)){
  				flag=true;
  				break;
  			}
  		}
  		return flag;
    }
    
    public boolean addRole(String userId, String rolekey){
    	User user = this.findByLoginName(userId);
    	Role role = roleService.findByNameOrKey(rolekey, rolekey);
    	List<Role> userroles=user.getRoles();
    	if(!userroles.contains(role)){
    		userroles.add(role);
    		userRoleMapper.save(user.getId(),role.getId());
    		return true;
    	}
    	return false;
    }

	
}
